# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
    QSizePolicy,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QMouseEvent, QIcon
import sys
import csv
import os
import json
import subprocess
import copy
from datetime import datetime
from functools import partial
from gui.controls import envs
from .. import config as Config
from ..utils import Utils
from .. import message_box as MBox
from ..dlg_model_params import DlgModeResetCls
from ..params_table import ParamsTable, OnlyOneRowTable

# from ..lazy_table import LazyTable
import math
from ..custom_widget import (
    SelectBox,
    RadioBtnGroup,
    MultRadioBtnGroup,
    LineEditFloat,
    LineEditInt,
)
from ..beam_and_mass_point.add_tank import DlgAddTank


def find_max_fourth_value(two_d_array, position):
    if not two_d_array:  # 如果数组为空，则返回None
        return None
    max_value = -math.inf  # 初始化最大值为负无穷大
    for sub_array in two_d_array:
        if len(sub_array) >= position + 1:  # 检查子数组长度是否至少为4
            fourth_value = sub_array[position]  # 提取第4位的值
            if fourth_value is None or fourth_value == "":  # 检查值是否为None
                continue
            if fourth_value > max_value:  # 比较并更新最大值
                max_value = fourth_value
    if max_value == -math.inf:
        return None
    return max_value  # 返回最大值


# 新增行必须使用 addRow()
class BarTable(ParamsTable):
    pasteState = Signal(str)

    def __init__(self, rows=0, columns=2, isLibrary=False, parent=None):
        super(BarTable, self).__init__(rows, columns, isLibrary, parent)

    def paste_tb_text(self):
        self.incorrectFormatRowList = []
        try:
            self.pasteState.emit("start")
            text = QApplication.clipboard().text()
            pasteList = text.split("\n")
            # pasteList = [item for item in pasteList if item and item.strip()]
            # 复制后，尾部会有一个空字符串数组，需要去掉
            if len(pasteList) > 0:
                if pasteList[-1] == "":
                    pasteList.pop(-1)
            pasteList2D = []
            for row in pasteList:
                pasteList2D.append(row.split("\t"))
                # pasteList2D.append(re.split(r"[\t]", row))
            rows = len(pasteList)
            isMutli = self.isMutli(pasteList2D)
            indexes = self.selectedIndexes()
            if indexes:
                # 选中单元后粘贴
                for index in indexes:
                    index = index
                    break
                r, c = index.row(), index.column()  # 拿到选中的第一个单元格
                residueColumn = self.columnCount() - c
                if residueColumn < len(pasteList2D[0]):
                    isPaste = MBox.confirm(
                        f"粘贴数据包含{len(pasteList2D[0])}列，但表格仅剩{residueColumn}列，超出部分不会被粘贴。是否继续？",
                    )
                    if isPaste:
                        self.seletedToPaste(
                            isMutli, rows, r, c, pasteList2D, indexes, text
                        )
                else:
                    self.seletedToPaste(isMutli, rows, r, c, pasteList2D, indexes, text)
            else:
                # 直接粘贴
                sameIdeDict = {}
                # # 判断数据是否有id
                # hasId = True
                # if Utils.toInt(pasteList2D[0][0]) == "":
                #     # 没有id
                #     hasId = False
                if self.uniqueFlagColumn != -1:
                    # if not hasId:
                    #     pasteList2D = [[""] + sublist for sublist in pasteList2D]
                    copyData = pasteList2D.copy()
                    tableDict = self.getTableDict()
                    for addIndex in range(len(copyData) - 1, -1, -1):  # 倒序遍历
                        csvRow = copyData[addIndex]

                        if (
                            csvRow[self.uniqueFlagColumn] is not None
                            and str(csvRow[self.uniqueFlagColumn]) in tableDict
                        ):
                            sameIdeDict[tableDict[str(csvRow[1])]["row"]] = csvRow
                            # self.updateRowData(
                            #     tableDict[str(csvRow[self.uniqueFlagColumn])]["row"],
                            #     csvRow,
                            # )
                            del pasteList2D[addIndex]
                    self.addMulitRows(
                        pasteList2D, isAddIncrementing=True, isPastOrImport=True
                    )
                    if len(sameIdeDict) > 0:
                        isIdSame = MBox.confirm(
                            text=f"目标包含{str(len(sameIdeDict))}个相同id的数据!",
                            title="替换或跳过",
                            sureText="替换",
                            cancelText="跳过",
                        )
                        if isIdSame:
                            for row, value in sameIdeDict.items():
                                self.updateRowData(row, value, True)
                else:
                    self.addMulitRows(pasteList2D, isPastOrImport=True)
            self.sortTableByID()
            if len(self.incorrectFormatRowList) > 0:
                MBox.warning(
                    text=f"数据格式不正确!",
                )
                self.incorrectFormatRowList = []
            self.pasteState.emit("end")
        except Exception as e:
            print(e)
            self.pasteState.emit("end")
            return


# 创建一个自定义的 QListWidget 类
class CustomListWidget(QListWidget):
    double_click_signal = Signal(int, object)

    def __init__(self):
        super().__init__()

    def mouseDoubleClickEvent(self, event: QMouseEvent):
        # 捕获双击事件
        super().mouseDoubleClickEvent(event)  # 调用父类的 mouseDoubleClickEvent 方法
        current_row = self.currentRow()  # 获取当前选中的行号
        selected_item = self.item(current_row)  # 获取当前选中的项目
        if selected_item:
            self.double_click_signal.emit(current_row, selected_item)


class CGridLayout(QGridLayout):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAlignment(Qt.AlignTop)


class DlgBeamAndMassPoint(DlgModeResetCls):
    beamAndMassPoint_save_signal = Signal(object)
    materialLibraryLocking_update_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("梁与质量点")
        self.resize(800, 900)

        self.isLoaded = False
        self.isImportOrPaste = False
        self.nodeNothingness = False
        self.lastMaterial = []
        self.widgetDict = {}
        self.tankRow = 0
        self.tankWidgetList = [
            "top_dir",
            "top_typ",
            "topTable",
            "bot_dir",
            "bot_typ",
            "botTable",
            "bot_quad",
            "tdId",
            "Mat",
            "Thick",
            "ringNum",
            "heightNum",
            "baffleTable",
            "topEnd",
            "botEnd",
            "dens",
            "radius",
            "radius_in",
            "tank_trj_mass",
        ]

        layout = QVBoxLayout()

        self.materialFile = Config.cachePath + "materialLibrary.json"
        self.materialData = Utils.read_json(self.materialFile)
        self.options = []
        if self.materialData:
            for key, _ in self.materialData.items():
                self.options.append({"title": key, "value": key})

        # 节点
        mainGroupBox = QGroupBox("节点")
        mainLayout = QVBoxLayout()
        mainGroupBox.setLayout(mainLayout)
        self.mainTable = ParamsTable(rows=0, columns=7)
        self.mainTable.verticalHeader().setVisible(True)
        self.mainTable.setHorizontalHeaderLabels(
            [
                "节点号",
                "x坐标",
                "y坐标",
                "z坐标",
                "质量",
                "半径",
                # "蒙皮厚度",
                # "等效厚度",
                # "材料",
                "位置说明",
            ]
        )
        self.mainTable.rowSetInt([0])
        self.mainTable.rowSetFloat([1, 2, 3, 4, 5, 6])
        # self.mainTable.rowSetSelect([8], options={"8": self.options})
        # self.mainTable.itemChanged.connect(self.conduitHeadChange)
        # self.mainTable.noEditHint = "该数据已入库，不可修改节点号！"
        self.mainTable.setAddIncrementing(True)
        self.mainTable.uniqueFlagColumn = 0
        # self.mainTable.pasteState.connect(self.pasteState)
        mainLayout.addWidget(self.mainTable)

        mainBtnLayout = QHBoxLayout()
        addMainBtn = QPushButton("新增")
        importMainBtn = QPushButton("导入csv")
        clearMainBtn = QPushButton("清空")

        mainBtnLayout.setAlignment(Qt.AlignCenter)
        mainBtnLayout.addWidget(addMainBtn)
        mainBtnLayout.addWidget(importMainBtn)
        mainBtnLayout.addWidget(clearMainBtn)
        mainLayout.addLayout(mainBtnLayout)

        addMainBtn.clicked.connect(partial(self.on_addBtn_clicked, self.mainTable))
        importMainBtn.clicked.connect(
            partial(self.on_importBtn_clicked, self.mainTable, "mainTable")
        )
        clearMainBtn.clicked.connect(partial(self.on_clearBtn_clicked, self.mainTable))
        layout.addWidget(mainGroupBox)

        # 单元
        barGroupBox = QGroupBox("单元")
        barLayout = QVBoxLayout()
        barGroupBox.setLayout(barLayout)

        self.barTable = BarTable(rows=0, columns=7)
        self.barTable.verticalHeader().setVisible(True)
        self.barTable.setHorizontalHeaderLabels(
            [
                "单元号",
                "节点1",
                "节点2",
                "单元外半径",
                "等效厚度",
                "蒙皮厚度",
                "材料",
            ]
        )

        self.barTable.rowSetInt([0, 1, 2])
        self.barTable.rowSetFloat([3, 4, 5])
        self.barTable.rowSetSelect([6], options={"6": self.options})
        self.barTable.itemChanged.connect(self.conduitHeadChange)
        self.barTable.setAddIncrementing(True)
        self.barTable.pasteState.connect(self.pasteState)
        self.barTable.noEditHint = "该数据已入库，不可修改单元号！"
        self.barTable.uniqueFlagColumn = 0
        barLayout.addWidget(self.barTable)

        barBtnLayout = QHBoxLayout()
        addBarBtn = QPushButton("新增")
        importBarBtn = QPushButton("导入csv")
        clearBarBtn = QPushButton("清空")

        barBtnLayout.setAlignment(Qt.AlignCenter)
        barBtnLayout.addWidget(addBarBtn)

        barBtnLayout.addWidget(importBarBtn)
        barBtnLayout.addWidget(clearBarBtn)
        barLayout.addLayout(barBtnLayout)
        layout.addWidget(barGroupBox)

        addBarBtn.clicked.connect(partial(self.on_addBtn_clicked, self.barTable))
        importBarBtn.clicked.connect(
            partial(self.on_importBtn_clicked, self.barTable, "barTable")
        )
        clearBarBtn.clicked.connect(partial(self.on_clearBtn_clicked, self.barTable))

        # 贮箱
        tankLayout = QHBoxLayout()
        layout.addLayout(tankLayout)

        tankNameGroupBox = QGroupBox("贮箱")
        tankNameLayout = QVBoxLayout()
        tankNameGroupBox.setLayout(tankNameLayout)

        tankBtnLayout = QHBoxLayout()
        addTankBarBtn = QPushButton()
        self.set_button_image(addTankBarBtn, "icons/plugins/qmodeling/add.png")
        addTankBarBtn.clicked.connect(self.on_addTankBarBtn_clicked)
        delTankBarBtn = QPushButton()
        self.set_button_image(delTankBarBtn, "icons/plugins/qmodeling/del.png")
        delTankBarBtn.clicked.connect(self.on_delTankBarBtn_clicked)
        tankBtnLayout.addWidget(addTankBarBtn)
        tankBtnLayout.addWidget(delTankBarBtn)
        tankBtnLayout.addStretch(1)
        tankNameLayout.addLayout(tankBtnLayout)

        self.tankListWidget = QListWidget()
        self.tankListWidget.model().rowsInserted.connect(self.on_item_count_changed)
        self.tankListWidget.model().rowsRemoved.connect(self.on_item_count_changed)
        self.tankListWidget.itemDoubleClicked.connect(
            self.on_tankListWidget_doubleClicked
        )

        self.tankListWidget.selectionModel().selectionChanged.connect(
            self.on_tankListWidget_Clicked
        )
        tankNameLayout.addWidget(self.tankListWidget)
        self.widgetDict["tankList"] = self.tankListWidget
        tankLayout.addWidget(tankNameGroupBox)

        tankContentGroupBox = QGroupBox("贮箱设置")
        tankContentLayout = QHBoxLayout()
        self.tankContentWidget = QWidget()
        tankContentLayout.addWidget(self.tankContentWidget)
        self.tankContentWidget.setVisible(False)
        tankContentWidgetLayout = QHBoxLayout()
        self.tankContentWidget.setLayout(tankContentWidgetLayout)
        tankContentGroupBox.setLayout(tankContentLayout)
        tankLayout.addWidget(tankContentGroupBox)
        tankLayout.setStretchFactor(tankNameGroupBox, 1)
        tankLayout.setStretchFactor(tankContentGroupBox, 4)
        panelLayout = QVBoxLayout()
        tankContentWidgetLayout.addLayout(panelLayout)

        topGroupBox = QGroupBox("上底")
        panelLayout.addWidget(topGroupBox)
        topLayout = QVBoxLayout()
        topGroupBox.setLayout(topLayout)
        topSelectLayout = QHBoxLayout()
        self.widgetDict["top_dir"] = SelectBox(
            options=[{"title": "凹", "value": "凹"}, {"title": "凸", "value": "凸"}],
            flag="top",
            key="top_dir",
            onChanged=lambda *args, **kwargs: self.concaveConvexChanged(
                self, *args, **kwargs
            ),
        )
        self.widgetDict["top_typ"] = SelectBox(
            options=[
                {"title": "椭球", "value": "椭球"},
                {"title": "三心球", "value": "三心球"},
                {"title": "半椭球", "value": "半椭球"},
                {"title": "椭球内嵌", "value": "椭球内嵌"},
            ],
            flag="top",
            key="top_typ",
            onChanged=lambda *args, **kwargs: self.ballChanged(self, *args, **kwargs),
        )
        topSelectLayout.addWidget(self.widgetDict["top_dir"])
        topSelectLayout.addWidget(self.widgetDict["top_typ"])
        topSelectLayout.addStretch(1)

        topPanelLayout = QHBoxLayout()
        topPanelTable = OnlyOneRowTable(rows=1, columns=1, isNoAddAndDel=True)
        topPanelTable.verticalHeader().setVisible(True)
        topPanelTable.setFixedHeight(130)
        # topPanelTable.setFixedSize(100, 130)
        # topPanelTable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)  # 恢复为默认的交互模式
        # topPanelTable.verticalHeader().setSectionResizeMode(QHeaderView.Interactive)  # 恢复为默认的交互模式
        # topPanelTable.setAllColumnWidth(60)
        topPanelTable.setHorizontalHeaderLabels(
            [
                "尺寸",
            ]
        )
        topPanelTable.rowSetFloat([0])
        topPanelTable.itemChanged.connect(partial(self.tableCellChanged, "topTable"))
        # self.setTableFixeHeight(topPanelTable, 20)
        self.widgetDict["topTable"] = topPanelTable

        self.topImage = QLabel()
        self.topImage.setAlignment(Qt.AlignCenter)
        # self.topImage.setFixedSize(100, 130)
        self.topImage.setFixedWidth(150)
        pixmap = QPixmap("")
        scaled_pixmap = pixmap.scaledToWidth(150, Qt.SmoothTransformation)
        self.topImage.setPixmap(scaled_pixmap)

        topPanelLayout.addWidget(topPanelTable)
        topPanelLayout.addStretch(1)
        topPanelLayout.addWidget(self.topImage)

        topLayout.addLayout(topSelectLayout)
        topLayout.addLayout(topPanelLayout)

        bottomGroupBox = QGroupBox("下底")
        panelLayout.addWidget(bottomGroupBox)
        bottomLayout = QVBoxLayout()
        bottomGroupBox.setLayout(bottomLayout)
        bottomSelectLayout = QHBoxLayout()
        bottomLayout.addLayout(bottomSelectLayout)
        self.widgetDict["bot_dir"] = SelectBox(
            options=[{"title": "凹", "value": "凹"}, {"title": "凸", "value": "凸"}],
            flag="bot",
            key="bot_dir",
            onChanged=lambda *args, **kwargs: self.concaveConvexChanged(
                self, *args, **kwargs
            ),
        )
        self.widgetDict["bot_typ"] = SelectBox(
            options=[
                {"title": "椭球", "value": "椭球"},
                {"title": "三心球", "value": "三心球"},
                {"title": "半椭球", "value": "半椭球"},
                {"title": "椭球内嵌", "value": "椭球内嵌"},
            ],
            flag="bot",
            key="bot_typ",
            onChanged=lambda *args, **kwargs: self.ballChanged(self, *args, **kwargs),
        )
        self.widgetDict["bot_quad"] = MultRadioBtnGroup(
            options=[{"title": "三维建模", "value": "三维建模"}],
            onChanged=lambda *args, **kwargs: self.tdChanged(*args, **kwargs),
        )
        bottomSelectLayout.addWidget(self.widgetDict["bot_dir"])
        bottomSelectLayout.addWidget(self.widgetDict["bot_typ"])
        bottomSelectLayout.addWidget(self.widgetDict["bot_quad"])

        self.tdWidget = QWidget()
        bottomLayout.addWidget(self.tdWidget)
        self.tdWidget.setVisible(False)
        tdLayout = QHBoxLayout()
        self.tdWidget.setLayout(tdLayout)

        eleNoBox = QGroupBox("固定长度")
        tdLayout.addWidget(eleNoBox)
        eleNoGridLayout = QGridLayout()
        eleNoBox.setLayout(eleNoGridLayout)
        ringNumLab = QLabel("环向个数")
        eleNoGridLayout.addWidget(ringNumLab, 0, 0)
        self.widgetDict["ringNum"] = LineEditFloat()
        eleNoGridLayout.addWidget(self.widgetDict["ringNum"], 0, 1)
        heightNumLab = QLabel("高度个数")
        eleNoGridLayout.addWidget(heightNumLab, 1, 0)
        self.widgetDict["heightNum"] = LineEditFloat()
        eleNoGridLayout.addWidget(self.widgetDict["heightNum"], 1, 1)

        tdGridlayout = QGridLayout()
        tdLayout.addLayout(tdGridlayout)
        tdIdLab = QLabel("初始编号")
        tdGridlayout.addWidget(tdIdLab, 0, 0)
        self.widgetDict["tdId"] = LineEditInt()
        tdGridlayout.addWidget(self.widgetDict["tdId"], 0, 1)
        matLab = QLabel("材料")
        tdGridlayout.addWidget(matLab, 1, 0)
        self.widgetDict["Mat"] = SelectBox(
            options=self.options,
            onChanged=lambda *args, **kwargs: self.MatChanged(self, *args, **kwargs),
        )
        tdGridlayout.addWidget(self.widgetDict["Mat"], 1, 1)
        thickLab = QLabel("厚度")
        tdGridlayout.addWidget(thickLab, 2, 0)
        self.widgetDict["Thick"] = LineEditFloat()
        tdGridlayout.addWidget(self.widgetDict["Thick"], 2, 1)

        bottomSelectLayout.addStretch(1)
        bottomPanelLayout = QHBoxLayout()
        bottomPanelTable = OnlyOneRowTable(rows=1, columns=1, isNoAddAndDel=True)
        # bottomPanelTable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)  # 恢复为默认的交互模式
        # bottomPanelTable.verticalHeader().setSectionResizeMode(QHeaderView.Interactive)  # 恢复为默认的交互模式
        # bottomPanelTable.setAllColumnWidth(60)
        bottomPanelTable.setHorizontalHeaderLabels(["尺寸"])
        bottomPanelTable.verticalHeader().setVisible(True)
        bottomPanelTable.setFixedHeight(130)
        # bottomPanelTable.setFixedSize(100, 130)
        bottomPanelTable.rowSetFloat([0])
        bottomPanelTable.itemChanged.connect(partial(self.tableCellChanged, "botTable"))
        # self.setTableFixeHeight(bottomPanelTable, 20)
        self.widgetDict["botTable"] = bottomPanelTable

        self.bottomImage = QLabel()
        self.bottomImage.setAlignment(Qt.AlignCenter)
        self.bottomImage.setFixedWidth(150)
        # self.bottomImage.setFixedSize(100, 130)
        pixmap = QPixmap("")
        scaled_pixmap = pixmap.scaledToWidth(150, Qt.SmoothTransformation)
        self.bottomImage.setPixmap(scaled_pixmap)

        bottomPanelLayout.addWidget(bottomPanelTable)
        bottomPanelLayout.addStretch(1)
        bottomPanelLayout.addWidget(self.bottomImage)
        bottomLayout.addLayout(bottomPanelLayout)

        gridLayout1 = QGridLayout()
        tankContentWidgetLayout.addLayout(gridLayout1)
        tankContentWidgetLayout.setStretchFactor(panelLayout, 3)
        tankContentWidgetLayout.setStretchFactor(gridLayout1, 2)

        baffleLayout = QGridLayout()
        baffleBox = QGroupBox("防晃板")
        baffleBox.setLayout(baffleLayout)
        gridLayout1.addWidget(baffleBox, 0, 0, 1, 2)
        self.baffleTable = ParamsTable(rows=0, columns=3)
        self.baffleTable.verticalHeader().setVisible(True)
        self.baffleTable.setHorizontalHeaderLabels(
            [
                "位置",
                "形式",
                "尺寸",
            ]
        )
        self.baffleTable.rowSetFloat([0, 2])
        self.baffleTable.rowSetSelect(
            [1],
            options={
                "1": [
                    {"title": "ring", "value": "ring"},
                    # {"title": "other", "value": "other"},
                ]
            },
        )
        self.baffleTable.itemChanged.connect(
            partial(self.tableCellChanged, "baffleTable")
        )
        baffleLayout.addWidget(self.baffleTable)
        self.widgetDict["baffleTable"] = self.baffleTable

        crossBox = QGroupBox("十字隔板的位置")
        gridLayout1.addWidget(crossBox, 1, 0, 1, 2)
        crossGridLayout = QGridLayout()
        crossBox.setLayout(crossGridLayout)
        topEndLab = QLabel("上端")
        crossGridLayout.addWidget(topEndLab, 0, 0)
        self.widgetDict["topEnd"] = LineEditFloat()
        crossGridLayout.addWidget(self.widgetDict["topEnd"], 0, 1)
        botEndLab = QLabel("下端")
        crossGridLayout.addWidget(botEndLab, 1, 0)
        self.widgetDict["botEnd"] = LineEditFloat()
        crossGridLayout.addWidget(self.widgetDict["botEnd"], 1, 1)

        densLab = QLabel("液体密度")
        gridLayout1.addWidget(densLab, 2, 0)
        self.widgetDict["dens"] = LineEditFloat()
        gridLayout1.addWidget(self.widgetDict["dens"], 2, 1)
        radiusLab = QLabel("贮箱外半径")
        gridLayout1.addWidget(radiusLab, 3, 0)
        self.widgetDict["radius"] = LineEditFloat()
        gridLayout1.addWidget(self.widgetDict["radius"], 3, 1)
        radiusInLab = QLabel("隧道管半径")
        gridLayout1.addWidget(radiusInLab, 4, 0)
        self.widgetDict["radius_in"] = LineEditFloat()
        gridLayout1.addWidget(self.widgetDict["radius_in"], 4, 1)
        tankTrjMassLab = QLabel("弹道贮箱非质量")
        gridLayout1.addWidget(tankTrjMassLab, 5, 0)
        self.widgetDict["tank_trj_mass"] = LineEditFloat()
        gridLayout1.addWidget(self.widgetDict["tank_trj_mass"], 5, 1)

        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")
        btnLayout2 = QHBoxLayout()
        btnLayout2.setAlignment(Qt.AlignCenter)
        btnLayout2.addWidget(okBtn)
        btnLayout2.addWidget(cancelBtn)
        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)
        layout.addLayout(btnLayout2)
        self.setLayout(layout)

        data = {}
        if Config.isLocation:
            self.cacheFile = Config.cachePath + "beamAndMassPoint.json"
            data = Utils.read_json(self.cacheFile)
        else:
            data = params.get("data") or {}
        self.updateUI(data)
        Utils.handleTableNoEdit(data=data.get("main") or [], table=self.mainTable)
        Utils.handleTableNoEdit(data=data.get("bar") or [], table=self.barTable)
        if Config.useLibraryLocking:
            self.lastMaterials = Utils.getTableLibrarysName(
                data=data.get("main"), column=8
            )
        envs.ipimas_changeMaterial = (
            lambda library, *args, **kwargs: self.libraryChange(
                library, *args, **kwargs
            )
        )
        
        # self.beamAndMassPoint_save_signal.emit({})

        self.setEditingFinished(self.tankWidgetList)
        if self.tankListWidget.count() > 0:
            item = self.tankListWidget.item(0)
            if item:
                # 设置选中状态
                self.tankListWidget.setCurrentItem(item)
                self.tankRow = 0
                currentData = item.data(Qt.UserRole)
                self.updateTankUI(currentData)

    def libraryChange(self, library):
        if self.isVisible():
            self.materialData = library

    def pasteState(self, state):
        if state == "start":
            self.nodeNothingnes = False
            self.isImportOrPaste = True
        else:
            self.isImportOrPaste = False
            if self.nodeNothingnes == True:
                self.nodeNothingnes = False
                MBox.warning(f"节点不存在！")

    def on_addBtn_clicked(self, table):
        table.add()

    def on_importBtn_clicked(self, table, flag):
        filePath = Utils.ImportFile()
        if filePath:
            _, fileExtension = os.path.splitext(filePath)
            fileExtension = fileExtension.lower()
            if fileExtension == ".json":
                self.loadTableList(filePath, table, flag)
            elif fileExtension == ".csv":
                self.load_csv(filePath, table, flag)

    def updateUI(self, data):
        self.isLoaded = False
        if data:
            try:
                main = data.get("main") or {}
                bar = data.get("bar") or {}
                for rowData in main:
                    self.mainTable.addRow(rowData=rowData)
                for rowData in bar:
                    self.barTable.addRow(rowData=rowData)
                tanks = data.get("tank") or {}
                for tank, value in tanks.items():
                    item = QListWidgetItem(tank)
                    value["name"] = tank
                    item.setData(Qt.UserRole, value)
                    self.tankListWidget.addItem(item)
                self.isLoaded = True
            except Exception as e:  # 捕获其他所有异常
                self.isLoaded = True

    def on_okBtn_clicked(self):
        main = self.mainTable.getTableDatatFirstNoNull()
        if isinstance(main, int):
            MBox.warning(f"节点 第{main}行节点号不可为空!")
            return
        if isinstance(main, str):
            MBox.warning(f"节点 第{main}行节点号已存在!")
            return
        bar = self.barTable.getTableDatatFirstNoNull()
        if isinstance(bar, int):
            MBox.warning(f"单元 第{bar}行单元号不可为空!")
            return
        if isinstance(bar, str):
            MBox.warning(f"单元 第{bar}行单元号已存在!")
            return
        # main = Utils.filter_dict_list(main)
        bar = Utils.filter_dict_list(bar)

        data = {"main": main, "bar": bar, "type": "bar_conm", "tank": {}}

        for i in range(self.tankListWidget.count()):
            item = self.tankListWidget.item(i)
            tankName = item.text()  # 获取项目的文本
            item_data = copy.deepcopy(item.data(Qt.UserRole))  # 获取项目的自定义数据
            if "bot_quad" not in item_data:
                item_data["bot_quad"] = {}
            del item_data["name"]
            data["tank"][tankName] = item_data

        filterDict = Utils.filterDictEmptyProperty(data)

        self.cacheFile = Config.cachePath + "beamAndMassPoint33.json"
        Utils.write_json(self.cacheFile, filterDict)
        if Config.isLocation:
            Utils.write_json(self.cacheFile, data)
        self.close()
        if Config.useLibraryLocking:
            unique_library = Utils.updateLockingLibrary(
                dataList=[[main, 8]],
                lastSelects=self.lastMaterials,
                library=self.materialData,
                file=Config.materialTable,
            )
            if unique_library:
                if hasattr(envs, "ipimas_changeLockMaterial"):
                    envs.ipimas_changeLockMaterial()
                self.materialLibraryLocking_update_signal.emit(unique_library)
        self.beamAndMassPoint_save_signal.emit(filterDict)

    def on_clearBtn_clicked(self, table):
        table.clearRow()

    # 双击
    def on_tankListWidget_doubleClicked(self):
        current_row = self.tankListWidget.currentRow()  # 获取当前选中的行号
        selected_item = self.tankListWidget.item(current_row)  # 获取当前选中的项目
        if selected_item:
            main = self.mainTable.getTableData()
            item_data = selected_item.data(Qt.UserRole)  # 获取项目的自定义数据
            names = []
            for i in range(self.tankListWidget.count()):
                if i != current_row:
                    item = self.tankListWidget.item(i)
                    names.append(item.text())
            dlgAddTank = DlgAddTank.show(
                parent=self,
                params={
                    "main": main,
                    "type": "edit",
                    "row": current_row,
                    "data": item_data,
                    "names": names,
                },
            )
            dlgAddTank.ok_signal.connect(self.on_update_tank)

    # 单击选中
    def on_tankListWidget_Clicked(self):
        current_row = self.tankListWidget.currentRow()  # 获取当前选中的行号
        selected_item = self.tankListWidget.item(current_row)  # 获取当前选中的项目
        currentData = selected_item.data(Qt.UserRole)
        self.tankRow = current_row
        self.updateTankUI(currentData)

    def on_delTankBarBtn_clicked(self):
        current_row = self.tankListWidget.currentRow()  # 获取当前选中的行号
        if current_row != -1:  # 如果有选中的项目
            isDel = MBox.confirm(
                "是否确认删除当前选中的贮箱?",
            )
            if isDel:
                self.tankListWidget.takeItem(current_row)  # 删除当前选中的项目
        else:
            MBox.warning("请选择要删除的行")

    def on_addTankBarBtn_clicked(self):
        main = self.mainTable.getTableData()
        names = []
        for i in range(self.tankListWidget.count()):
            item = self.tankListWidget.item(i)
            names.append(item.text())
        dlgAddTank = DlgAddTank.show(parent=self, params={"main": main, "names": names})
        dlgAddTank.ok_signal.connect(self.on_update_tank)

    def on_update_tank(self, type, row, data):
        if type == "add":
            item = QListWidgetItem(data.get("name"))
            item.setData(Qt.UserRole, data)
            self.tankListWidget.addItem(item)
            # self.updateTankUI(data)
        else:
            item = self.tankListWidget.item(row)
            item.setText(data.get("name"))
            item.setData(Qt.UserRole, data)
            itemData = item.data(Qt.UserRole)
            itemData["name"] = data.get("name")
            itemData["ids"] = data.get("ids")
            item.setData(Qt.UserRole, itemData)
        if item:
            # 设置选中状态
            self.tankListWidget.setCurrentItem(item)

    def clearTanktTableUI(self):
        # self.updateBotTyp("")
        # self.updateBallTable("", "topTable")
        # self.updateBallTable("", "botTable")
        # self.widgetDict["top_dir"].setValue("")
        # self.widgetDict["top_typ"].setValue("")
        self.widgetDict["topTable"].fillRowData(row=0, rowData=[None])
        # self.widgetDict["bot_dir"].setValue("")
        # self.widgetDict["bot_typ"].setValue("")
        self.widgetDict["botTable"].fillRowData(row=0, rowData=[None])

    def updateTankUI(self, data):
        self.clearTanktTableUI()
        # print("updateTankUI=", data)
        # 处理显示切换
        self.updateBotTyp(data.get("bot_dir"))
        self.updateBallTable(data.get("top_typ"), "topTable")
        self.updateBallTable(data.get("bot_typ"), "botTable")
        bot_quad = data.get("bot_quad")
        self.tdWidget.setVisible(True if bot_quad else False)

        # 上底
        self.widgetDict["top_dir"].setValue(data.get("top_dir"))
        self.widgetDict["top_typ"].setValue(data.get("top_typ"))
        topData = data.get("top_siz") or []
        topList = [[item] for item in topData]
        for i, topRowData in enumerate(topList):
            self.widgetDict["topTable"].fillRowData(row=i, rowData=topRowData)
        # 下底
        self.widgetDict["bot_dir"].setValue(data.get("bot_dir"))
        self.widgetDict["bot_typ"].setValue(data.get("bot_typ"))
        botData = data.get("bot_siz") or []
        botList = [[item] for item in botData]
        for i, botRowData in enumerate(botList):
            self.widgetDict["botTable"].fillRowData(row=i, rowData=botRowData)
        # for botRowData in botData:
        # self.widgetDict["botTable"].fillRowData(row=0,rowData=botData)
        if bot_quad:
            self.widgetDict["bot_quad"].setValue(["三维建模"])
            self.widgetDict["tdId"].setValue(bot_quad.get("id"))
            self.widgetDict["Mat"].setValue(bot_quad.get("mat"))
            self.widgetDict["Thick"].setValue(bot_quad.get("thick"))
            eleNo = bot_quad.get("ele_no") or []
            for i, ele in enumerate(eleNo):
                if i == 0:
                    self.widgetDict["ringNum"].setValue(ele)
                elif i == 1:
                    self.widgetDict["heightNum"].setValue(ele)
        else:
            self.widgetDict["bot_quad"].setValue([])
        # 防晃板
        baffle = data.get("baffle") or []
        self.widgetDict["baffleTable"].setRowCount(0)
        for baf in baffle:
            self.widgetDict["baffleTable"].addRow(rowData=baf)
        # 十字隔板
        self.widgetDict["topEnd"].setValue(None)
        self.widgetDict["botEnd"].setValue(None)
        cross = data.get("cross") or []
        for i, cro in enumerate(cross):
            if i == 0:
                self.widgetDict["topEnd"].setValue(cro)
            elif i == 1:
                self.widgetDict["botEnd"].setValue(cro)
        # 其他
        self.widgetDict["dens"].setValue(data.get("dens"))
        self.widgetDict["radius"].setValue(data.get("radius"))
        self.widgetDict["radius_in"].setValue(data.get("radius_in"))
        self.widgetDict["tank_trj_mass"].setValue(data.get("tank_trj_mass"))

    def setEditingFinished(self, list):
        for widgetKey in list:
            widget = self.widgetDict[widgetKey]
            if isinstance(widget, QLineEdit):
                widget.editingFinished.connect(
                    partial(self.on_text_changed, flag=widgetKey)
                )

    def on_text_changed(self, flag, *args, **kwargs):
        item = self.tankListWidget.item(self.tankRow)  # 获取当前选中的项目
        if not item:
            return
        data = item.data(Qt.UserRole)
        if flag == "topEnd":
            if "cross" not in data:
                data["cross"] = [None, None]
            if len(data["cross"]) < 2:
                data["cross"].extend([None] * (2 - len(data["cross"])))
            data["cross"][0] = self.widgetDict[flag].getValue()
        elif flag == "botEnd":
            if "cross" not in data:
                data["cross"] = [None, None]
            if len(data["cross"]) < 2:
                data["cross"].extend([None] * (2 - len(data["cross"])))
            data["cross"][1] = self.widgetDict[flag].getValue()
        elif flag == "bot_quad":
            value = self.widgetDict["bot_quad"].getValue()
            if value and "bot_quad" not in data:
                data["bot_quad"] = {"ele_no": [None, None]}
        elif flag == "ringNum":
            if "ele_no" not in data["bot_quad"]:
                data["bot_quad"]["ele_no"] = [None, None]
            if len(data["bot_quad"]["ele_no"]) < 2:
                data["bot_quad"]["ele_no"].extend(
                    [None] * (2 - len(data["bot_quad"]["ele_no"]))
                )
            data["bot_quad"]["ele_no"][0] = self.widgetDict[flag].getValue()
        elif flag == "heightNum":
            if "ele_no" not in data["bot_quad"]:
                data["bot_quad"]["ele_no"] = [None, None]
            if len(data["bot_quad"]["ele_no"]) < 2:
                data["bot_quad"]["ele_no"].extend(
                    [None] * (2 - len(data["bot_quad"]["ele_no"]))
                )
            data["bot_quad"]["ele_no"][1] = self.widgetDict[flag].getValue()
        elif flag == "tdId":
            data["bot_quad"]["id"] = self.widgetDict[flag].getValue()
        elif flag == "Mat":
            data["bot_quad"]["mat"] = self.widgetDict[flag].getValue()
        elif flag == "Thick":
            data["bot_quad"]["thick"] = self.widgetDict[flag].getValue()
        elif flag == "baffleTable":
            data["baffle"] = self.widgetDict[flag].getTableData()
        elif flag == "botTable":
            values = [row[0] for row in self.widgetDict[flag].getTableData()]
            data["bot_siz"] = values
        elif flag == "topTable":
            values = [row[0] for row in self.widgetDict[flag].getTableData()]
            data["top_siz"] = values
        else:
            data[flag] = self.widgetDict[flag].getValue()
        item.setData(Qt.UserRole, data)

    def load_csv(self, filename, table, flag):
        if flag == "barTable":
            data = Utils.loadCsv(
                filename,
                labList=[
                    "单元号",
                    "节点1",
                    "节点2",
                    "单元外半径",
                    "等效厚度",
                    "蒙皮厚度",
                    "材料",
                ],
            )
        else:
            data = Utils.loadCsv(
                filename,
                labList=[
                    "节点号",
                    "x坐标",
                    "y坐标",
                    "z坐标",
                    "质量",
                    "半径",
                    "蒙皮厚度",
                    "等效厚度",
                    "材料",
                    "位置说明",
                ],
            )
        if data:
            copyCsvData = data.copy()
            idDict = table.getTableDict()
            try:
                self.nodeNothingnes = False
                if flag == "barTable":
                    self.isImportOrPaste = True
                for addIndex in range(len(copyCsvData) - 1, -1, -1):  # 倒序遍历
                    csvRow = copyCsvData[addIndex]
                    # 更新同id
                    if (
                        csvRow[0] is not None
                        and csvRow[0] != ""
                        and str(csvRow[0]) in idDict
                    ):
                        table.updateRowData(idDict[str(csvRow[0])]["row"], csvRow)
                        del data[addIndex]
                table.addMulitRows(data)
                if flag == "barTable":
                    self.isImportOrPaste = False
                if self.nodeNothingnes == True:
                    self.nodeNothingnes = False
                    MBox.warning(f"节点不存在！")
            except Exception as e:
                if flag == "barTable":
                    self.isImportOrPaste = False
                    self.nodeNothingnes = False
                print(e)

    def loadTableList(self, file, table):
        data = Utils.read_json(file)
        for rowData in data:
            table.addRow(rowData=rowData)

    def setTableFixeHeight(self, table, patchHeight=0):
        total_height = table.rowHeight(0)
        horizontal_header_height = table.horizontalHeader().height()
        table.setFixedHeight(total_height + horizontal_header_height + patchHeight)

    def conduitHeadChange(self, item):
        if not self.isLoaded:
            return
        row = item.row()
        column = item.column()
        if column != 1 and column != 2:
            return
        text = self.barTable.item(row, column).text()
        value = Utils.toIntOrNone(text)
        nodeDict = self.mainTable.getColumnDict()
        if value is not None and value not in nodeDict:
            item.setText("")
            if not self.isImportOrPaste:
                MBox.warning(f"设置的节点号不存在！")
            else:
                self.nodeNothingnes = True

    def tableCellChanged(self, key, *args, **kwargs):
        self.on_text_changed(key)
        # if not self.isLoaded:
        #     return

    def updatePanel(self, list):
        # 删除标签页
        for k, _ in self.panelPages.items():
            if k not in list:
                index = self.tabs.indexOf(self.panelPages[k])
                if index != -1:
                    self.tabs.removeTab(index)
                self.panelPages[k] = None
                self.panelWidget[k] = None
        # 新增标签页
        for panel in list:
            if panel not in self.panelPages or self.panelPages[panel] is None:
                self.panelPages[panel] = QWidget()
                self.tabs.addTab(self.panelPages[panel], panel)
                self.createPanelPage(panel)

    def concaveConvexChanged(self, *args, **kwargs):
        if args[3] == "bot":
            self.updateBotTyp(args[1])
        self.on_text_changed(args[4])

    def updateBotTyp(self, value):
        if value == "凸":
            self.widgetDict["bot_typ"].updateItem(
                [
                    {"title": "椭球", "value": "椭球"},
                    {"title": "三心球", "value": "三心球"},
                    {"title": "椭球内嵌", "value": "椭球内嵌"},
                    {"title": "半椭球", "value": "半椭球"},
                    {"title": "球锥球", "value": "球锥球"},
                    {"title": "锥加凹球", "value": "锥加凹球"},
                ]
            )
        else:
            self.widgetDict["bot_typ"].updateItem(
                [
                    {"title": "椭球", "value": "椭球"},
                    {"title": "三心球", "value": "三心球"},
                    {"title": "椭球内嵌", "value": "椭球内嵌"},
                    {"title": "半椭球", "value": "半椭球"},
                ]
            )

    def ballChanged(self, *args, **kwargs):
        key = f"{args[3]}Table"
        self.updateBallTable(args[1], key)
        self.on_text_changed(args[4])

    def updateBallTable(self, value, key):
        if value == "椭球":
            self.widgetDict[key].setCustomRowCount(1)
        elif value == "三心球":
            self.widgetDict[key].setCustomRowCount(5)
        elif value == "球锥球":
            self.widgetDict[key].setCustomRowCount(6)
        elif value == "锥加凹球":
            self.widgetDict[key].setCustomRowCount(4)
        elif value == "椭球内嵌":
            self.widgetDict[key].setCustomRowCount(2)
        elif value == "半椭球":
            self.widgetDict[key].setCustomRowCount(3)
        else:
            self.widgetDict[key].setCustomRowCount(1)

    def tdChanged(self, *args, **kwargs):
        tdValue = self.widgetDict["bot_quad"].getValue()
        if tdValue and len(tdValue) >= 1:
            self.tdWidget.setVisible(True)
        else:
            self.tdWidget.setVisible(False)
        self.on_text_changed("bot_quad")

    def MatChanged(self, *args, **kwargs):
        self.on_text_changed("Mat")

    def on_item_count_changed(self):
        if self.tankListWidget.count() > 0:
            self.tankContentWidget.setVisible(True)
        else:
            self.tankContentWidget.setVisible(False)

    def set_button_image(self, button, image_path):
        """设置按钮的图片，并保持等比宽高，同时设置边距"""
        pixmap = QPixmap(image_path)
        if pixmap.isNull():
            print("Error: Unable to load image.")
            return

        # 等比缩放图片到指定大小（15x15像素）
        scaled_pixmap = pixmap.scaled(
            15, 15, Qt.KeepAspectRatio, Qt.SmoothTransformation
        )

        # 将 QPixmap 转换为 QIcon
        icon = QIcon(scaled_pixmap)

        # 设置按钮图标和大小
        button.setIcon(icon)  # 使用 QIcon 设置图标
        button.setIconSize(scaled_pixmap.size())  # 设置图标大小
        # button.setFixedSize(20, 20)  # 强制设置按钮的宽高为25像素（15 + 2 * 5）
        button.setStyleSheet(
            "QPushButton { min-width: 20px !important; min-height: 20px !important; max-width: 20px !important; max-height: 20px !important; }"
        )


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = BeamAndMassPointDialog()
#     window.show()
#     sys.exit(app.exec_())
